#include <iostream>
#include <json/json.h>
#include <json/value.h>
#include <json/reader.h>
#include "const.h"
#include "ConfigMgr.h"
#include "hiredis.h"
#include "RedisMgr.h"
#include "MysqlMgr.h"
#include "AsioIOServicePool.h"
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <boost/asio.hpp>
#include "StatusServiceImpl.h"

void RunServer() {
	auto& cfg = ConfigMgr::Inst();
	std::string server_address(cfg["StatusServer"]["Host"] + ":" + cfg["StatusServer"]["Port"]);
	StatusServiceImpl service;
	grpc::ServerBuilder builder;
	builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
	builder.RegisterService(&service);
	std::unique_ptr<grpc::Server>server(builder.BuildAndStart());
	std::cout << "Server listening on " << server_address << std::endl;
	boost::asio::io_context ioc;
	boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
	signals.async_wait([&server](const boost::system::error_code& error, int signal_number) {
		if (!error) {
			std::cout << "Shutting down server......" << std::endl;
			server->Shutdown();
		}
	});
	std::thread([&ioc]() {ioc.run(); }).detach();
	server->Wait();
	ioc.stop();
}
int main() {
	try {
		RunServer();
	}
	catch (std::exception& e) {
		std::cout << "Error: " << e.what() << std::endl;
		return	EXIT_FAILURE;
	}
}
